import genFetch from './genFetch'

export const getParams = function getParams(params = {}) {
  let newParams = { ...params }
  let text = ''
  Object.keys(JSON.parse(JSON.stringify(newParams))).forEach(e => {
    if (newParams[e] !== undefined && newParams[e] !== 'null') {
      text += e + '=' + newParams[e] + '&'
    }
  })
  if (text) {
    text = '?' + text
  }
  return text
}

export const bodyParams = function (params = {}) {
  return JSON.stringify({
    ...params
  })
}

export const postAction = function (url, params = {}, config) {
  const type = Object.prototype.toString.call(params)
  return genFetch(
    url,
    {
      method: 'POST',
      body: type == '[object FormData]' ? params : bodyParams(params)
    },
    config
  )
}

export const putAction = function (url, params = {}, config = {}) {
  const type = Object.prototype.toString.call(params)
  return genFetch(
    url,
    {
      method: 'PUT',
      body: type == '[object FormData]' ? params : bodyParams(params)
    },
    config
  )
}

export const getAction = function (url, params = {}, config = {}) {
  return genFetch(
    url + getParams(params),
    {
      method: 'GET',
    },
    { 
      ...config,
      headers: {
        'content-Type': ''
      } 
    }
  )
}

export const deleteAction = function (url, params = {}) {
  const type = Object.prototype.toString.call(params)
  return genFetch(url, {
    method: 'DELETE',
    body: type == '[object FormData]' ? params : bodyParams(params)
  })
}

export const loginAction = function (url, config) {
  return genFetch(
    url,
    {
      method: 'POST',
      headers: {
        Authorization:
          'Basic c3p4Y19hcHA6OThkMzVjODEtOGYwZS00MjM4LWJjODYtYjkwMjYwMmVlZTAz'
      }
    },
    config
  )
}

export const tokenAction = function (url) {
  return fetch(`api/${url}`, {
    headers: new Headers({
      Authorization:
        'Basic c3p4Y19hcHA6OThkMzVjODEtOGYwZS00MjM4LWJjODYtYjkwMjYwMmVlZTAz'
    })
  }).then(e => {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async resolve => {
      resolve({
        ...(await e.json()),
        status: e.status
      })
    })
  })
}

export const getQiniuToken = () => {
  return getAction('/api/h5/fileUpload/getUploadToken')
}

export default {
  postAction,
  getAction,
  putAction,
  deleteAction,
  loginAction,
  getParams,
  tokenAction,
  getQiniuToken
}
